//
//  XJSetPhoneNumViewController.m
//  XinJiangMall
//
//  Created by Tzyang on 2018/4/12.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "ZYTextField.h"
#import "XJCodeView.h"

typedef void(^XJModifyPhoneViewClickSendCodeButtonBlock) (void);
typedef void(^XJModifyPhoneViewClickSureButtonBlock)(void);

@interface XJModifyPhoneView:UIView <XJCodeDelegate>
@property(nonatomic, strong) UIButton *button;
@property(nonatomic, strong) ZYTextField *phoneTextField; // 手机号输入框
@property(nonatomic, strong) ZYTextField *codeTextField; // 验证码输入框
@property(nonatomic, strong) XJCodeView *codeView; // 获取验证码按钮

/**点击发送验证码按钮block*/
@property(nonatomic, copy) XJModifyPhoneViewClickSendCodeButtonBlock sendCodeBlock;
/**点击下一步、确定修改按钮block*/
@property(nonatomic, copy) XJModifyPhoneViewClickSureButtonBlock sureButtonBlock;

- (instancetype)initWithFrame:(CGRect)frame placeholder:(NSString *)placehoder buttonTitle:(NSString *)btnTitle;

@end
@implementation XJModifyPhoneView
- (instancetype)initWithFrame:(CGRect)frame placeholder:(NSString *)placehoder buttonTitle:(NSString *)btnTitle {

    self = [super initWithFrame:frame];
    
    if (self) {
        [self setupVeiw];
        
        [self.button setTitle:btnTitle forState:(UIControlStateNormal)];
        self.phoneTextField.placeholder = placehoder;
    }
    return self;
}

- (void)setupVeiw {
    [self addSubview:self.phoneTextField];
    [self addSubview:self.codeTextField];
    [self addSubview:self.button];
}

- (ZYTextField *)phoneTextField {
    if (!_phoneTextField) {
        _phoneTextField = [[ZYTextField alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 50) placeholder:@"请输入原手机号" keyboardType:(UIKeyboardTypePhonePad) leftViewImageName:@"login_phone" textEntry:NO];
        [_phoneTextField addTarget:self action:@selector(change_phoneTextDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    }
    return _phoneTextField;
}

- (ZYTextField *)codeTextField {
    if (!_codeTextField) {
        _codeTextField = [[ZYTextField alloc] initWithFrame:CGRectMake(0, 50, self.frame.size.width, 50) placeholder:@"请输入验证码" keyboardType:(UIKeyboardTypePhonePad) leftViewImageName:@"login_verify" textEntry:NO];
        
        // 添加右边视图
        UIView *rightView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 100, 50)];
        [rightView addSubview:self.codeView];
        _codeTextField.rightView  = rightView;
        _codeTextField.rightViewMode = UITextFieldViewModeAlways;
    }
    return _codeTextField;
}

- (XJCodeView *)codeView {
    if (!_codeView) {
        // (50-30) / 2 = 10
        _codeView = [[XJCodeView alloc] initWithTime:60 frame:CGRectMake(0, 10, 100, 30)];
        _codeView.delegate = self;
        _codeView.codeBtn.backgroundColor = MAINS_COLOR;
        _codeView.codeBtn.userInteractionEnabled = NO;
    }
    return _codeView;
}


- (UIButton *)button {
    if (!_button) {
        _button = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [_button setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        _button.layer.cornerRadius = 10;
        _button.layer.masksToBounds = YES;
        _button.backgroundColor = XJCOLOR_RGB(255, 216, 68);
        
        // 设置frame
        _button.frame = CGRectMake(0, self.size.height - 100, self.bounds.size.width, 50);
        [_button addTarget:self action:@selector(nextButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
    }
    return _button;
}

// 监听输入的手机号的变化
- (void)change_phoneTextDidChange:(ZYTextField *)phoneTF {
    if ([phoneTF.text isPhoneNumber]) {
        self.codeView.codeBtn.userInteractionEnabled = YES;
        self.codeView.codeBtn.backgroundColor = MAIN_COLOR;
    }else {
        self.codeView.codeBtn.userInteractionEnabled = NO;
        self.codeView.codeBtn.backgroundColor = MAINS_COLOR;
    }
}


- (void)nextButtonAction {
    if (self.sureButtonBlock) {
        self.sureButtonBlock();
    }
}

- (void)getCheckCode:(NSString *)checkCode {
    if (self.sendCodeBlock) {
        self.sendCodeBlock();
    }
}
@end

#pragma mark - ============类分割线==============

typedef void(^XJModifySuccessViewbackHomepageBlock) (void);
// 修改成功类
@interface XJModifySuccessView:UIView
@property(nonatomic, strong) UIImageView *iv;
@property (nonatomic, strong) UILabel *modifySuccessLabel;
@property(nonatomic, strong) UIButton *backHomepageButton; //返回首页

@property(nonatomic, strong) XJModifySuccessViewbackHomepageBlock backhomepageBlock;

@end

@implementation XJModifySuccessView
- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        [self setupView];
    }
    return self;
}
- (void)setupView {
    [self addSubview:self.iv];
    [self addSubview:self.modifySuccessLabel];
    [self addSubview:self.backHomepageButton];
}

- (UIImageView *)iv{
    if (!_iv) {
        _iv = [[UIImageView alloc] init];
        _iv.image = [UIImage imageNamed:@""];
        _iv.backgroundColor = [UIColor redColor];
    }
    return _iv;
}
- (UILabel *)modifySuccessLabel {
    if (!_modifySuccessLabel) {
        _modifySuccessLabel = [[UILabel alloc] init];
        _modifySuccessLabel.font = XJFONTSET_R(13);
        _modifySuccessLabel.text = @"修改成功";
        _modifySuccessLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _modifySuccessLabel;
}
- (UIButton *)backHomepageButton {
    if (!_backHomepageButton) {
        _backHomepageButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        _backHomepageButton.layer.masksToBounds = YES;
        _backHomepageButton.layer.cornerRadius = 10;
        [_backHomepageButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
        [_backHomepageButton setTitle:@"返回首页" forState:(UIControlStateNormal)];
        _backHomepageButton.backgroundColor = XJCOLOR_RGB(255, 216, 68);
        
        [_backHomepageButton addTarget:self action:@selector(backhomepageButtonAction) forControlEvents:(UIControlEventTouchUpInside)];
        
    }
    return _backHomepageButton;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [self.iv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top).offset(50);
        make.centerX.equalTo(self.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(200, 200));
    }];
    [self.modifySuccessLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.iv.mas_bottom).offset(30);
        make.centerX.equalTo(self.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(100, 20));
    }];
    
    [self.backHomepageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.modifySuccessLabel.mas_bottom).offset(20);
        make.centerX.equalTo(self.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(100, 40));
    }];
}
- (void)backhomepageButtonAction {
    if (self.backhomepageBlock) {
        self.backhomepageBlock();
    }
}

@end
#pragma mark - ============类分割线==============

#import "XJSetPhoneNumViewController.h"

@interface XJSetPhoneNumViewController ()
@property(nonatomic, strong) XJModifyPhoneView *nextView; //修改手机号下一步view
@property(nonatomic, strong) XJModifyPhoneView *confirmModifyView; // 确认修改手机号view
@property(nonatomic, strong) XJModifySuccessView *modifySuccessVeiw;// 修改成功view

@end

@implementation XJSetPhoneNumViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navTitle = @"修改手机号";
    
    [self setupView];
}

- (void)setupView {
    [self.view addSubview:self.nextView];
    [self.view addSubview:self.confirmModifyView]; // 默认隐藏
    [self.view addSubview:self.modifySuccessVeiw]; // 默认隐藏。
}

#pragma mark - lazy
- (XJModifyPhoneView *)nextView {
    if (!_nextView) {
        _nextView = [[XJModifyPhoneView alloc] initWithFrame:CGRectMake(15, 64, KWidth - 30, 300) placeholder:@"请输入原手机号" buttonTitle:@"下一步"];
        
        // 发送验证码
        XJWeakSelf(self)
        _nextView.sendCodeBlock = ^{
            // 调用接口。
            [weakself requestNextSendCode];
        };
        
        // 点击下一步
        _nextView.sureButtonBlock = ^{
            [weakself requestNext];
        };
    }
    return _nextView;
}


- (XJModifyPhoneView *)confirmModifyView {
    if (!_confirmModifyView) {
        _confirmModifyView = [[XJModifyPhoneView alloc] initWithFrame:CGRectMake(15, 64, KWidth - 30, 300) placeholder:@"请输入新手机号" buttonTitle:@"确认修改"];
        
        _confirmModifyView.hidden = YES;
        
        XJWeakSelf(self)
        // 点击发送验证码
        _confirmModifyView.sendCodeBlock = ^{
            [weakself requestModifySendCode];
        };
        
        //确认修改按钮事件
        _confirmModifyView.sureButtonBlock = ^{
            [weakself requestConfirmModify];
        };
    }
    return _confirmModifyView;
}

- (XJModifySuccessView *)modifySuccessVeiw {
    if (!_modifySuccessVeiw) {
        _modifySuccessVeiw = [[XJModifySuccessView alloc] initWithFrame:CGRectMake(15, 64, KWidth-30, 400)];
        _modifySuccessVeiw.hidden = YES;
        
        // 返回首页
        XJWeakSelf(self)
        _modifySuccessVeiw.backhomepageBlock = ^{
            XJLog(@"点击返回首页");
            [weakself.navigationController popViewControllerAnimated:YES];
        };
    }
    return _modifySuccessVeiw;
}


#pragma mark - 网络请求 并切换视图状态
// 下一步view发送验证码
- (void)requestNextSendCode{
    // 修改手机验证码
    [XJHttpTool requestSendCodeWithPhone:self.nextView.phoneTextField.text type:@"editphone" successH:^(id responseObjc) {
        NSNumber *code = responseObjc[@"code"];
        
        if ([code isEqualToNumber:@0]) {
            [JRToast showWithText:@"验证码已经发送"];
        }
    } failureH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}

// 下一步验证
- (void)requestNext {
    
    NSString *phone = self.nextView.phoneTextField.text;
    NSString *codeStr = self.nextView.codeTextField.text;
    if ([NSString isEmptyString:phone]) {
        [JRToast showWithText:@"请输入手机号"];
        return;
    }
    
    if ([NSString isEmptyString:codeStr]) {
        [JRToast showWithText:@"请输入验证码"];
        return;
    }
    XJLog(@"%@==%@",phone,codeStr);
    // 调用接口。
    [XJHttpTool requestVerifyCodeWithPhone:phone code:codeStr type:@"editphone" successH:^(id responseObjc) {
        NSNumber *code = responseObjc[@"code"];
        
        
        
        if ([code isEqualToNumber:@0]) {
            // 跳转 下一步
            //网络请求是异步的需要回到主线程刷新不然不好使
            dispatch_async(dispatch_get_main_queue(), ^{
                self.confirmModifyView.hidden = NO;
                self.nextView.hidden = YES;
                self.modifySuccessVeiw.hidden = YES;
            });
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
        }
    } failureH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];

    }];
}

// 确认修改发送验证码
- (void)requestModifySendCode{
    
    NSString *phone = self.confirmModifyView.phoneTextField.text;
    
    // bind 绑定新手机号 不知道是否好使
    [XJHttpTool requestSendCodeWithPhone:phone type:@"bind" successH:^(id responseObjc) {
        NSNumber *code = responseObjc[@"code"];
        
        if ([code isEqualToNumber:@0]) {
            [JRToast showWithText:@"验证码已经发送"];
        }
    } failureH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}
// 确认修改
- (void)requestConfirmModify {
    NSString *phone = self.confirmModifyView.phoneTextField.text;
    NSString *codeStr = self.confirmModifyView.codeTextField.text;

    if ([NSString isEmptyString:phone]) {
        [JRToast showWithText:@"请输入手机号"];
        return;
    }
    
    if ([NSString isEmptyString:codeStr]) {
        [JRToast showWithText:@"请输入验证码"];
        return;
    }
 
    [XJHttpTool requestVerifyCodeWithPhone:phone code:codeStr type:@"bind" successH:^(id responseObjc) {
        
        NSNumber *code = responseObjc[@"code"];
        
        if ([code isEqualToNumber:@0]) {
            // 跳转 下一步            
            //网络请求是异步的需要回到主线程刷新不然不好使
            dispatch_async(dispatch_get_main_queue(), ^{
                self.confirmModifyView.hidden = YES;
                self.nextView.hidden = YES;
                self.modifySuccessVeiw.hidden = NO;
            });
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
        }
    } failureH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
